package com.ushine.web.security.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ushine.web.component.exception.BaseErrorInfoInterface;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yls
 * @Date: 2022/02/13 21:44
 * @Description: 统一的登录情况处理器
 * @Version 1.0
 */
@Component
public class SecurityResponse implements Serializable {

    private static final String CHARSET = "application/json;charset=utf-8";

    public void getResponse(HttpServletResponse response, int code, String msg, Object data) throws IOException {
        response.setContentType(CHARSET);
        Map<String, Object> resp = new HashMap<>(3);
        resp.put("code", code);
        resp.put("msg", msg);
        resp.put("data", data);
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }

    public void getResponse(HttpServletResponse response, int code, String msg) throws IOException {
        response.setContentType(CHARSET);
        Map<String, Object> resp = new HashMap<>(3);
        resp.put("code", code);
        resp.put("msg", msg);
        resp.put("data", "");
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }

    public void getResponse(HttpServletResponse response, BaseErrorInfoInterface baseErrorInfoInterface) throws IOException {
        response.setContentType(CHARSET);
        Map<String, Object> resp = new HashMap<>(3);
        resp.put("code", baseErrorInfoInterface.getErrorCode());
        resp.put("msg", baseErrorInfoInterface.getErrorMsg());
        resp.put("data", "");
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }
}
